<?php
	include_once('PHPExcel/Classes/PHPExcel.php');
	class UsersController extends  BaseController{

		protected  $_className ="Users";

		public function getUsersList($filter=null){
			return parent::getEntityList($filter);
		}

		public function saveUser($post_json = null,$transaction = null){
			$rtn = null;
			$token =AccessTokenManager::getAccessToken();

			if (empty($token)) {
				throw new CustomerException("微信接口异常，请检查网络设置",4);
			}


			//$isNew=true说明是新增用户，否则是修改用户
			parent::save($post_json ,$transaction);
			$this->_bean->reload();

			$shop = AbstractBean::LoadBean("Shop",$this->_bean->get("departmentid"));		
			$wechatId = $shop->get("wechat_id");
			if($wechatId!=null){
				$localDeptId = $this->_bean ->get("departmentid");
				$this->_bean ->set("departmentid",$wechatId);
				$authenticate = $this->_bean ->get("authenticate");
				//新增用户
				if($authenticate== null || $authenticate==0){
					$rtn = json_decode(AbstractBean::invokeFunc($this->_bean,"createUser",new User($token)));
				}
				else{//修改用户
					$rtn = json_decode(AbstractBean::invokeFunc($this->_bean,"updateUser",new User($token)));
				}
				if ($rtn->success!=1 && $rtn->success!="1") {
					throw new CustomerException($rtn->errmsg,5);
				}

				else{
					$this->_bean->set("authenticate",1);
	            	$this->_bean->set("departmentid",$localDeptId);
					$this->_bean->save();
				}	
			}
			
		}

		public function deleteUser($id){
			$conn = new CreateConnection();
			$token =$conn->getAccessToken(CORPID,CORPSECRET);
			if (empty($token)) {
				throw new CustomerException("微信接口异常，请检查网络设置",4);
			}
			$user = parent::getEntityByid($id);
			parent::delete($id);
			
			$w_user = new User($token);
			$rtn =  $w_user -> deleteUser($user->get("userid"));
			if ($rtn->success!=1 && $rtn->success!="1") {
				throw new CustomerException($rtn->errmsg,5);
			}
			
		}

		public function sync2Wechat($userId){
	        $errors = array();
	        $rtn=null;
	        $token = AccessTokenManager::getAccessToken();
	        
	        $user = AbstractBean::LoadBean("Users");
	        $filter = new SqlFilter();
	        if($userId!=null){
				$filter->addFilter("id",EQUALS,$userId);
			}
	        $userList = $user->fetchBeanList();
	       	 
	        for($i=0;$i<count($userList);$i++){
	        	$localDeptId=$userList[$i]->get("departmentid");
	        	$userList[$i]->set("departmentid",$userList[$i]->get("wechat_id"));
	       	 	$authenticate  = $userList[$i]->get("authenticate");
	       	 	if($authenticate== null || $authenticate=="" ||$authenticate==0){
	       	 		$rtn = json_decode(AbstractBean::invokeFunc($userList[$i],"createUser",new User($token)));
	       	 	}
	       	 	else{
	       	 		$rtn = json_decode(AbstractBean::invokeFunc($userList[$i],"updateUser",new User($token)));
	       	 	}
	       	 	print_r($rtn);
	            if($rtn->errcode == 0){
	            	$userList[$i]->set("authenticate",1);
	            	$userList[$i]->set("departmentid",$localDeptId);
					$userList[$i]->save();
	            }
	            else{
	            	array_push($errors,"[".$userList[$i]->get("userid")."]:".$rtn->errmsg);
	            }
	            
	        }
	        return  $errors;
	    }

   
	    public function batchImport($excel,$transaction){
	    
	      if(!empty($excel) &&count($excel)>0){
	        
	          $objReader = PHPExcel_IOFactory::createReader('Excel2007');
	          $objReader->setReadDataOnly(true);
	          $objPHPExcel = $objReader->load($excel[0]["file_path"]);
	          $objPHPExcel->setActiveSheetIndex(0);
	          $objWorksheet = $objPHPExcel->getActiveSheet();         
	          $highestRow = $objWorksheet->getHighestRow(); 
	          $highestColumn = $objWorksheet->getHighestColumn(); 
	          $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); 
	          $deptList = array();              

	          for ($row = 2; $row <= $highestRow; $row++) { 
	                $bean = AbstractBean::LoadBean("Users");
	                $mobile = $objWorksheet->getCellByColumnAndRow(2, $row)->getValue();
	                if($mobile ==  null ||  $mobile==""){
	                  continue;
	                }
	                if(!AbstractBean::UniqueValidate("Users","mobile",$mobile)){
	                  throw new CustomerException("手机号码[".$mobile."]已经存在",3);
	                }
	                $sex=$objWorksheet->getCellByColumnAndRow(1, $row)->getValue();
	                $gender = $sex== "男" ? 1:2;
	                $bean->set("userid",$mobile);
	                $bean->set("name",$objWorksheet->getCellByColumnAndRow(0, $row)->getValue());
	                $bean->set("gender",$gender);
	                $bean->set("mobile",$mobile);
	                $bean->set("position",$objWorksheet->getCellByColumnAndRow(3, $row)->getValue());
	                $bean->set("dept_name",$objWorksheet->getCellByColumnAndRow(4, $row)->getValue());
	                $bean->set("email",$objWorksheet->getCellByColumnAndRow(5, $row)->getValue());
	                $bean->set("weixinid",$objWorksheet->getCellByColumnAndRow(6, $row)->getValue());
	                $bean->save();
	         }
	         AbstractBean::executeSql("update tb_users set departmentid = (select top 1 id from tb_shop where tb_shop.name = tb_users.dept_name ) where departmentid is null");
	         $this->sync2Wechat();

	      }
	  }


	}
?>